package org.demo.cnck.controller.api;

import org.demo.cnck.controller.error.BussinessException;
import org.demo.cnck.controller.vm.HttpMessage;
import org.demo.cnck.controller.vm.LoginVm;
import org.demo.cnck.controller.vm.MessageHelper;
import org.demo.cnck.dao.constant.SystemConstant;
import org.demo.cnck.dao.domain.User;
import org.demo.cnck.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * Created by cdyoue on 2018/11/20.
 */
@Controller
public class SystemController {
    @Autowired
    private HttpSession httpSession;

    @Autowired
    private UserService userService;

    @PostMapping("system/login")
    public ResponseEntity<HttpMessage> login(LoginVm loginVm) {
        User user = userService.findByUserName(loginVm.getUsername());
        if (null == user) {
            throw new BussinessException("用户名不存在");
        }
        if (!Objects.equals(user.getPassword(), loginVm.getPassword())) {
            throw new BussinessException("密码错误");
        }

        httpSession.setAttribute(SystemConstant.USER_SESSION_KEY, user);
        return ResponseEntity.ok(MessageHelper.OK().message("登录成功").build());
    }


    @GetMapping("system/logout")
    public String logout() {
        httpSession.removeAttribute(SystemConstant.USER_SESSION_KEY);
        return "login";
    }

    @PostMapping("system/regist")
    public ResponseEntity<HttpMessage> regist(User user) {
        User byUserName = userService.findByUserName(user.getUsername());
        if (null != byUserName) {
            throw new BussinessException("该用户名已存在");
        }
        userService.save(user);
        return ResponseEntity.ok(MessageHelper.OK().message("注册").build());
    }


}
